import jsonpath from "./jsonpath";

export function replace(json: Object, modify: Record<string,string|{type:string,value:any}>){
  Object.keys(modify).forEach((key) => {
    console.log("modifymodify", key);
    // @ts-ignore
    jsonpath.apply(json, key, (originalValue:string) => {
      let modifyValue = modify[key];
      let modifyStr = '';
      let type = "string";
      if (typeof modifyValue === "object") {
        type = modifyValue.type;
        modifyStr = modifyValue.value;
      }

      if (typeof modifyValue === "number" || typeof modifyValue == "boolean") {
        return modifyValue;
      }
      const replaceResult = modifyStr.replace(/{(.*?)}/g, (match, p1) => {
        // @ts-ignore
        let value = jsonpath.query(json, p1, 1)[0];
        if (!value) {
          return `{${p1}}`.replace(/{value}/g,originalValue);
        }
        return typeof value === "object" ? JSON.stringify(value) : value;
      });
      if (type === "object") {
        return JSON.parse(replaceResult);
      } else if (type === "number") {
        return Number(replaceResult);
      }
      return replaceResult;
    });
  });
  return json;
}
export default { replace };
